package org.hitchhike.web.front.controller;

import javax.servlet.http.HttpServletRequest;

import org.hitchhike.common.domain.BaseEntity;
import org.hitchhike.common.web.controller.BaseController;
import org.hitchhike.core.domain.Order;
import org.hitchhike.core.domain.OrderDetail;
import org.hitchhike.core.domain.User;
import org.hitchhike.core.enums.Constant;
import org.hitchhike.core.exception.BaseException;
import org.hitchhike.core.exception.ErrorInfo;
import org.hitchhike.core.form.ReserveForm;
import org.hitchhike.core.service.OrderDetailService;
import org.hitchhike.core.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping(value = "/front/order")
public class OrderController extends BaseController<BaseEntity, Long> {
  private Logger logger = LoggerFactory.getLogger(getClass());

  @Autowired
  private OrderService orderService;
  @Autowired
  private OrderDetailService orderDetailService;

  public static final String CANCEL_OK = "取消成功。";
  public static final String CANCEL_ERROR = "取消失败。";
  public static final String CONFIRM_OK = "确认成功。";
  public static final String CONFIRM_ERROR = "确认失败。";
  public static final String PAYMENT_OK = "付款成功。";
  public static final String PAYMENT_ERROR = "付款成功。";

  /* ====================订单==================== */
  /**
   * 订单查询
   */
  @RequestMapping(value = "/{orderState}", method = RequestMethod.GET)
  public String order(Model model, @PathVariable String orderState, Integer page) {
    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    model.addAttribute("page", orderService.findAll(page, user.getId(), orderState));
    model.addAttribute("active", orderState);
    model.addAttribute("nav_active", "order");
    return viewName("order");
  }

  /**
   * 取消订单
   */
  @RequestMapping(value = "/cancel/{id}", method = RequestMethod.GET)
  public String cancel(RedirectAttributes redirectAttributes, @PathVariable Long id) {
    ErrorInfo<String> r = new ErrorInfo<>();
    try {
      orderService.updateCancel(id);

      r.setCode(ErrorInfo.OK);
      r.setMessage(CANCEL_OK);
    } catch (Exception e) {
      logger.error(e.getMessage());
      r.setCode(ErrorInfo.ERROR);
      r.setMessage(CANCEL_ERROR);
    }
    redirectAttributes.addFlashAttribute("r", r);
    return redirectToUrl(viewName("/12"));
  }

  /**
   * 确认订单
   */
  @RequestMapping(value = "/confirm/{id}", method = RequestMethod.GET)
  public String confirm(RedirectAttributes redirectAttributes, @PathVariable Long id) {
    ErrorInfo<String> r = new ErrorInfo<>();
    try {
      orderService.updateConfirm(id);

      r.setCode(ErrorInfo.OK);
      r.setMessage(CONFIRM_OK);
    } catch (Exception e) {
      logger.error(e.getMessage());
      r.setCode(ErrorInfo.ERROR);
      r.setMessage(CONFIRM_ERROR);
    }
    redirectAttributes.addFlashAttribute("r", r);
    return redirectToUrl(viewName("/12"));
  }

  /**
   * 付款订单
   */
  @RequestMapping(value = "/payment/{id}", method = RequestMethod.GET)
  public String payment(RedirectAttributes redirectAttributes, @PathVariable Long id) {
    ErrorInfo<String> r = new ErrorInfo<>();
    try {
      orderService.updatePayment(id);

      r.setCode(ErrorInfo.OK);
      r.setMessage(PAYMENT_OK);
    } catch (Exception e) {
      logger.error(e.getMessage());
      r.setCode(ErrorInfo.ERROR);
      r.setMessage(PAYMENT_ERROR);
    }
    redirectAttributes.addFlashAttribute("r", r);
    return redirectToUrl(viewName("/12"));
  }


  /* ====================车票==================== */
  /**
   * 车票查询
   */
  @RequestMapping(value = "/ticket/{state}", method = RequestMethod.GET)
  public String ticket(Model model, @PathVariable String state, Integer page) {
    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    model.addAttribute("page", orderDetailService.findPage(page, user.getId(), state));
    model.addAttribute("active", state);
    model.addAttribute("nav_active", "ticket");
    return viewName("/ticket");
  }

  /**
   * 车票取消
   */
  @RequestMapping(value = "/ticket/cancel/{id}", method = RequestMethod.GET)
  public String ticketCancel(RedirectAttributes redirectAttributes, @PathVariable Long id) {
    ErrorInfo<String> r = new ErrorInfo<>();
    try {
      orderDetailService.cancel(id);

      r.setCode(ErrorInfo.OK);
      r.setMessage(CANCEL_OK);
    } catch (Exception e) {
      r.setCode(ErrorInfo.ERROR);
      r.setMessage(CANCEL_ERROR);
    }
    redirectAttributes.addFlashAttribute("r", r);
    return redirectToUrl(viewName("/ticket/1"));
  }


  /**
   * 车票确认
   */
  @RequestMapping(value = "/ticket/confirm/{id}", method = RequestMethod.GET)
  public String ticketConfirm(RedirectAttributes redirectAttributes, @PathVariable Long id) {
    ErrorInfo<String> r = new ErrorInfo<>();
    try {
      orderDetailService.confirm(id);

      r.setCode(ErrorInfo.OK);
      r.setMessage(CONFIRM_OK);
    } catch (Exception e) {
      r.setCode(ErrorInfo.ERROR);
      r.setMessage(CONFIRM_ERROR);
    }
    redirectAttributes.addFlashAttribute("r", r);
    return redirectToUrl(viewName("/ticket/1"));
  }

  /**
   * 车票付款
   */
  @RequestMapping(value = "/ticket/payment/{id}", method = RequestMethod.GET)
  public String ticketPayment(RedirectAttributes redirectAttributes, @PathVariable Long id) {
    ErrorInfo<String> r = new ErrorInfo<>();
    try {
      orderDetailService.payment(id);

      r.setCode(ErrorInfo.OK);
      r.setMessage(PAYMENT_OK);
    } catch (Exception e) {
      r.setCode(ErrorInfo.ERROR);
      r.setMessage(PAYMENT_ERROR);
    }
    redirectAttributes.addFlashAttribute("r", r);
    return redirectToUrl(viewName("/ticket/1"));
  }

  /* ====================其他==================== */
  /**
   * 详细页面
   */
  @RequestMapping(value = "/reserve/{type}/{id}", method = RequestMethod.GET)
  public String reserve(Model model, @PathVariable String type, @PathVariable Long id) {
    Order order = orderService.get(id);
    if (order == null) {
      throw new BaseException("没找到您查询的订单...");
    }
    model.addAttribute("order", order);
    model.addAttribute("type", type);
    return viewName("reserve");
  }

  /**
   * 保存订单明细
   */
  @RequestMapping(value = "/reserve/save", method = RequestMethod.POST)
  public String save(ReserveForm reserveForm, HttpServletRequest request) {
    Order order = orderService.get(reserveForm.getId());
    if (order == null) {
      throw new BaseException("没找到您查询的订单...");
    }

    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    try {
      orderDetailService.save(new OrderDetail(order, user, Constant.ORDER_DETAIL_STATE_1));
      if (order.getOrderProcess() == Constant.ORDER_PROCESS_0) {
        order.setOrderProcess(Constant.ORDER_PROCESS_1);
        orderService.update(order);
      }
    } catch (Exception e) {
      throw new BaseException(e.getMessage());
    }

    return redirectToUrl(viewName("/ticket/1"));
  }

}
